import router, { asyncRoutes } from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import store from './store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404', '/register'] // no redirect whitelist
// 全局前置路由守卫
router.beforeEach(async(to, from, next) => {
  // 启动进度条
  NProgress.start()

  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.id) {
        await store.dispatch('user/getUserInfoAsync')
        const { data } = await store.dispatch('user/getMyPermission')
        const filterRoutes = asyncRoutes.filter(item => {
          return data.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 全局后置路由守卫
router.afterEach(() => {
  // 进度条结束
  NProgress.done()
})
